resource "alicloud_db_instance" "main" {
  count                = var.number_of_instances == "" ? 1 : 0  
  engine               = var.rds_engine
  engine_version       = var.rds_engine_version
  instance_type        = var.rds_instance_type
  instance_storage     = var.rds_instance_storage
  instance_name        = var.rds_instance_name
  instance_charge_type = var.rds_instance_charge_type
  period               = var.rds_period
  vswitch_id           = var.rds_vswitch_id[count.index]
  zone_id              = var.rds_zone_id
  zone_id_slave_a      = var.rds_zone_id_slave_a
  zone_id_slave_b      = var.rds_zone_id_slave_b
  security_ips         = var.rds_security_ips
  security_group_ids   = var.rds_security_group_ids
  security_ip_mode     = var.rds_security_ip_mode
  monitoring_period    = var.rds_monitoring_period
  auto_renew           = var.rds_auto_renew
  auto_renew_period    = var.rds_auto_renew_period
  maintain_time        = var.rds_maintain_time
  dynamic "parameters" {
    for_each           = var.rds_parameters
    content {
      name             = lookup(parameters.value, "name", null)
      value            = parameters.value.value
    }
  }  
  tags                 = var.tags
  auto_upgrade_minor_version    = var.rds_auto_upgrade_minor_version
}

resource "alicloud_db_connection" "main" {
  count                = var.enable_rds_internet ? 1 : 0   
  instance_id          = alicloud_db_instance.main.0.id
  connection_prefix    = alicloud_db_instance.main.0.instance_name
}

resource "alicloud_db_backup_policy" "main" {
  count                           = var.enable_rds_backup ? 1 : 0  
  instance_id                     = alicloud_db_instance.main.0.id
  preferred_backup_period         = var.rds_backup_period
  preferred_backup_time           = var.rds_backup_time
  backup_retention_period         = var.rds_retention_period
  enable_backup_log               = var.rds_log_backup
  log_backup_retention_period     = var.rds_log_retention_period
}

data "alicloud_kms_plaintext" "main" {
  ciphertext_blob         = var.rds_kms_password
}

resource "alicloud_rds_account" "main" {
  db_instance_id              = alicloud_db_instance.main.0.id
  account_name                = var.rds_username
  account_password            = var.rds_password
  kms_encrypted_password      = data.alicloud_kms_plaintext.main.ciphertext_blob
  account_type                = var.rds_account_type
}